use std::fs;
use csv::Reader;
use anyhow;

use serde::{Deserialize, Serialize};

#[derive(Debug,Deserialize,Serialize)]
struct User{
    #[serde(rename = "number")]
    number: String,
    #[serde(rename = "name")]
    name: String,
    #[serde(rename = "email")]
    email: String,
}

pub fn csv_to_json(input: &str , output: &str) -> anyhow::Result<()>{
    let mut reader = Reader::from_path(input)?;
    // 这里把Reader::from_path(structopt.input).unwrap(); 换成 '?' 相当于是
    // match reader {
    //     Ok(v) => ...,
    //     Err(e) => ...,
    // }
    let mut result_vec = Vec::with_capacity(128);
    for element in reader.deserialize() {
        let record: User = element?;
        println!("{:?}",record);
        result_vec.push(record)
    }

    //上述的for循环 和下面的迭代器是等价的

    // let record = reader.deserialize()
    //     .map(|e| e.unwrap())
    //     .collect::<Vec<User>>();
    // println!("{:?}",record)

    //转换为json
    let json_result  = serde_json::to_string_pretty(&result_vec)?;

    //输出json文件
    fs::write(output,json_result)?;
    Ok(())
}